import time

import pymysql
import sys
import json
import ibm_db
from datetime import datetime, timedelta
from apscheduler.triggers import cron

def getIntervalSeconds(cronVal):
    base = datetime.now()
    print(base)
    # cronVal = '0 0/5 * * * ?'
    splitCron = cronVal.split(" ")
    for i in range(0, len(splitCron)):
        if splitCron[i] == '?':
            splitCron[i] = None
    myCron = cron.CronTrigger(second=splitCron[0],
                              minute=splitCron[1],
                              hour=splitCron[2],
                              day_of_week=splitCron[3],
                              month=splitCron[4],
                              year=splitCron[5]);
    firstTime = myCron.get_next_fire_time(base, base)
    print(firstTime)
    base.replace(tzinfo=firstTime.tzinfo)
    firstTime = firstTime.replace(tzinfo=None)
    # base=base.replace(tzinfo=pytz.timezone(str(firstTime.tzinfo)))
    secondTime = myCron.get_next_fire_time(firstTime + timedelta(seconds=1), firstTime + timedelta(seconds=1))
    secondTime = secondTime.replace(tzinfo=None)
    print(secondTime)
    result = (secondTime - firstTime).seconds
    return result;
class alarm:
    def __init__(self, data: dict = None):
        # self.type = data['type']
        # self.host = data['host']
        # self.port = data['port']
        # self.user = data['user']
        # self.password = data['password']
        # self.database = data['database']
        # self.schema = data['schema']
        # self.table = data['table']
        self.type = "db2"
        self.host = "172.26.2.56"
        self.port = "50000"
        self.user = "db2admin"
        self.password = "p@Sec0.db2,"
        self.database = "KGLT1"
        self.schema = "KGLT1"
        self.table = "ALARM_DATABASE_OPEARATOR"
        self.info = data['data']
        self.alarm_pos = data['alarm_pos']
        self.alarm_level = data['alarm_level']
        self.alarm_area = data['alarm_area']
        self.db = None
        self.sql = None
        self.name = '预警'
        self.cron=data['sys_triggerContent']
        self.ruleId=data['sys_ruleId']
    def mysql_connect(self):
        self.db = pymysql.connect(host=self.host,
                                  user=self.user,
                                  passwd=self.password,
                                  port=int(self.port),
                                  charset='utf8')

    def db2_connect(self):
        datasource = "DATABASE={0};HOSTNAME={1};PORT={2};PROTOCOL=TCPIP;UID={3};PWD={4};".format(self.database,
                                                                                                 self.host,
                                                                                                 self.port,
                                                                                                 self.user,
                                                                                                 self.password)
        self.db = ibm_db.connect(datasource, "", "")

    def create_sql(self):
        #先查询判断间隔超过周期1.5倍再插入
        output_time = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
        self.sql = "INSERT INTO {0}.{1} (RECORD_TIME,NAME,RECORD_DATA,ALARM_POS,ALARM_LEVEL,ALARM_AREA) VALUES('{2}','{3}','{4}','{5}','{6}','{7}');".format(self.schema,
                                                                         self.table,
                                                                         output_time,
                                                                         self.name,
                                                                         self.info,
                                                                         self.alarm_pos,
                                                                         self.alarm_level,
                                                                         self.alarm_area)

    def insert(self):
        self.create_sql()
        if self.type == 'mysql':
            self.mysql_connect()
            cursor = self.db.cursor()
            cursor.execute(self.sql)
            self.db.commit()
            self.db.close()
        else:
            self.db2_connect()
            ibm_db.exec_immediate(self.db, self.sql)
            ibm_db.commit(self.db)
            ibm_db.close(self.db)


def main():
    try:
        arg1 = sys.argv[1]
        dict1 = json.loads(arg1)
        alarm_actor = alarm(dict1)
        alarm_actor.insert()
        output = {'result': 'insert success'}
        print(json.dumps(output))
    except Exception as err:
        print(err)


if __name__ == '__main__':
    main()